package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dto.WmUserDto;
import com.heima.model.wemedia.pojo.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by ZYJ on 2021/5/25 18:37
 */
@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {
    /**
     * 自媒体用户登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(WmUserDto dto) {
        if(StringUtils.isEmpty(dto.getName())||StringUtils.isEmpty(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"用户名或密码不能为空");
        }
        WmUser wmUser = this.getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, dto.getName()));
        if(wmUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户名不存在");
        }
        String password = dto.getPassword();
        String salt = wmUser.getSalt();
        //生成加盐加密后密码
        String realPassword = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        if(!realPassword.equals(wmUser.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //比对完成 生成token
        Map<String, Object> map = new HashMap<>();
        String token = AppJwtUtil.getToken(wmUser.getId().longValue());
        //敏感数据不能返回
        wmUser.setPassword("");
        wmUser.setSalt("");
        map.put("token",token);
        map.put("user",wmUser);
        return ResponseResult.okResult(map);
    }


}
